﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Linq;
using System.Collections.Generic;

namespace 简易批量图片转换器
{
    public partial class MainForm : Form
    {
        private List<string> FileList = new List<string>();
        
        private ManualResetEvent manualReset = new ManualResetEvent(true);

        public MainForm()
        {
            InitializeComponent();
        }

        private void ChangeLabelPosition()
        {
            var OldPosition = label1.Width;
            label1.Text = $"{progressBar1.Value}/{progressBar1.Maximum}";
            label1.Left += OldPosition - label1.Width;
        }

        private void RefreshList()
        {
            FileList.Clear();
            FileListBox.Items.Clear();
            GetItems(InputDirBox.Text);
            FileListBox.Items.AddRange(FileList.ToArray());
            progressBar1.Maximum = FileList.Count;
            ChangeLabelPosition();
        }

        private void Convert2JPG(string path)
        {
            try
            {
                if (!File.Exists(ChangeExstion(path)) || !SkipOpt.Checked)
                {
                    var img = Image.FromFile(path);
                    img.Save(ChangeExstion(path), ImageFormat.Jpeg);
                    img.Dispose();
                }
                if (DelOpt.Checked)
                {
                    File.Delete(path);
                }
            }
            catch(Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        private void GetItems(string path)
        {
            try
            {
                foreach (var dir in Directory.GetDirectories(path))
                {
                    GetItems(dir);
                }
                var files = Directory.GetFiles(path).Where(x => x.EndsWith(".bmp") || x.EndsWith(".png"));
                FileList.AddRange(files);
            }
            catch(Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        private string ChangeExstion(string path) => Path.ChangeExtension(path, ".jpg");

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            if (DialogResult.OK == folderBrowserDialog1.ShowDialog())
            {
                InputDirBox.Text = folderBrowserDialog1.SelectedPath;
                RefreshList();
            }
        }

        private void RefreshBtn_Click(object sender, EventArgs e)
        {
            if (!backgroundWorker1.IsBusy && InputDirBox.TextLength != 0)
            {
                RefreshList();
            }
        }

        private void StartBtn_Click(object sender, EventArgs e)
        {
            if (backgroundWorker1.IsBusy)
            {
                manualReset.Set();
            }
            else
            {
                if (FileList.Count > 0)
                {
                    BrowserBtn.Enabled = false;
                    DelOpt.Enabled = false;
                    SkipOpt.Enabled = false;
                    backgroundWorker1.RunWorkerAsync(progressBar1.Maximum);
                }
            }
        }

        private void PauseBtn_Click(object sender, EventArgs e)
        {
            if (backgroundWorker1.IsBusy)
            {
                manualReset.Reset();
            }
        }

        private void StopBtn_Click(object sender, EventArgs e)
        {
            backgroundWorker1.CancelAsync();
            manualReset.Set();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            var current = 0;
            foreach (var item in FileList)
            {
                if (backgroundWorker1.CancellationPending)
                {
                    e.Cancel = true; return;
                }
                Convert2JPG(item);
                backgroundWorker1.ReportProgress(++current);
                manualReset.WaitOne();
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
            ChangeLabelPosition();
            toolStripStatusLabel1.Text = "正在操作" + FileList[e.ProgressPercentage - 1];
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            BrowserBtn.Enabled = true;
            DelOpt.Enabled = true;
            SkipOpt.Enabled = true;
            RefreshList();
            if (e.Cancelled)
            {
                progressBar1.Value = 0;
                ChangeLabelPosition();
                toolStripStatusLabel1.Text = "操作被用户取消";
            }
            else
            {
                toolStripStatusLabel1.Text = "操作完成";
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            DelOpt.Checked = Properties.Settings.Default.DelSrc;
            SkipOpt.Checked = Properties.Settings.Default.SkipFile;
        }

        private void DelOpt_CheckedChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.DelSrc = DelOpt.Checked;
        }

        private void SkipOpt_CheckedChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.SkipFile = SkipOpt.Checked;
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Properties.Settings.Default.Save();
        }
    }
}